#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, subprocess, time
import signal

class SerialEmulator(object):
    def __init__(self, device_port='/tmp/ttydevice', client_port='/tmp/ttyclient'):
        self.device_port = device_port
        self.client_port = client_port
        cmd=['socat','-d','-d','PTY,link=%s,raw,echo=0' %
                self.device_port, 'PTY,link=%s,raw,echo=0' % self.client_port]
        print('emulator start 1: %s, 2: %s' %(device_port, client_port) )
        self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        self.err = ''
        self.out = ''

    def __del__(self):
        self.stop()

    def stop(self):
        self.proc.kill()
        self.out, self.err = self.proc.communicate()

    def wait(self):
        self.proc.wait()

    def ctrl_c(self):
        self.proc.send_signal(signal.SIGINT)

#if __name__ == "__main__":
def run(devlist):
    print(devlist)
    emulators = []
    for node in devlist:
        devname = node.split(':')#eg: /tmp/ttyUSB0:/tmp/ttyUSB1
        emulators.append(SerialEmulator(devname[0],devname[1]))

    try:
        print('emulator start and wait...')
        for emulator in emulators:
            emulator.wait()
    except KeyboardInterrupt:
        for emulator in emulators:
            emulator.ctrl_c()
